﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Web;
using ShareMarking.Service;
using ShareMarking.Entity;

namespace ShareMarking.Interface
{
    public class NC_Sync
    {
        //protected string httpstr = "http://ncsearch.baiytfp.com";  //正式
        //protected string httpstr = "http://nc.baiytfp.com";
        //protected string access_key_id = "xiaoma";
        //protected string access_key_secret = "xiaoma_secret";

        protected string httpstr;
        protected string access_key_id;
        protected string access_key_secret;

        public NC_Sync(string httpstr, string keyid, string keysecret)
        {
            this.httpstr = httpstr;
            this.access_key_id = keyid;
            this.access_key_secret = keysecret;
        }

        public int GetNCCount()
        {
            #region sign
            var timestamp = DateTime.Now.Ticks - 621355968000000000;
            var parameters = new Dictionary<string, string>();
            parameters.Add("access_key_id", access_key_id);
            parameters.Add("timestamp", timestamp.ToString());
            var request_str = BuildQuery(parameters);
            var signature = HMACSHA1Encrypt(request_str, access_key_secret);
            #endregion
            parameters.Add("signature", signature);
            var postData = Encoding.UTF8.GetBytes(BuildQuery(parameters));
            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            click.Encoding = Encoding.UTF8;
            string result = click.Post(this.httpstr + "/ncsearch/ncapi/nc_count.do", postData);
            var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Interface.nccountresults>(result);
            return resultentity.result;
        }

        public ShareMarking.Interface.ncresults GetNC(int currentpage, int gopage, int pagesize, int rownum)
        {
            #region sign
            var timestamp = DateTime.Now.Ticks - 621355968000000000;
            var parameters = new Dictionary<string, string>();
            parameters.Add("access_key_id", access_key_id);
            parameters.Add("currentpage", currentpage.ToString());
            parameters.Add("gopage", gopage.ToString());
            parameters.Add("name-value", "");
            parameters.Add("pagesize", pagesize.ToString());
            parameters.Add("rownum", rownum.ToString());
            parameters.Add("timestamp", timestamp.ToString());
            var request_str = BuildQuery(parameters);
            var signature = HMACSHA1Encrypt(request_str, access_key_secret);
            #endregion

            #region 请求
            parameters.Add("signature", signature);
            var postData = Encoding.UTF8.GetBytes(BuildQuery(parameters));
            ComLib.WebClientHelper click = new ComLib.WebClientHelper();
            click.Encoding = Encoding.UTF8;
            string result = click.Post(httpstr + "/ncsearch/ncapi/nc_list.do", postData);
            var resultentity = ComLib.JsonHelper.JsonDeserialize<ShareMarking.Interface.ncresults>(result);
            #endregion

            return resultentity;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名为空的参数
                if (!string.IsNullOrEmpty(name))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(HttpUtility.UrlEncode(name, Encoding.UTF8));
                    postData.Append("=");
                    postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }

        public static string HMACSHA1Encrypt(string EncryptText, string EncryptKey)
        {
            //HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(EncryptKey));
            //byte[] RstRes = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(EncryptText));
            //StringBuilder EnText = new StringBuilder();
            //foreach (byte Byte in RstRes)
            //{
            //    EnText.AppendFormat("{0:x2}", Byte);
            //}
            //return EnText.ToString();
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key = Encoding.UTF8.GetBytes(EncryptKey);
            byte[] dataBuffer = Encoding.UTF8.GetBytes(EncryptText);
            byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
            return Convert.ToBase64String(hashBytes);
        }
    }

    public class NC_QRCode
    {
        protected string httpstr;
        protected string signserect;

        public NC_QRCode(string httpstr, string signserect)
        {
            this.httpstr = httpstr;
            this.signserect = signserect;
        }

        public void Sync_QrCode()
        {
            //先得到所有的需要更新二维码的NC
            var nclist = nc_ncuserService.Instance.Get_Entity_byWhere(Entity.nc_ncuser._.isneedupdate == true, null);
            ComLib.LogLib.Log4NetBase.Log("3、==========================更新NC二维码===========数量:" + nclist.Count);
            nclist.ForEach(o =>
            {
                try
                {
                    if (o.state == "活跃员工" || o.state == "休眠员工")
                    {
                        #region 活跃员工的处理

                        var has = qr_QrCodeRelateService.Instance.Get_IsExist_ByWhere(
                            qr_QrCodeRelate._.qr_Type == 1 && qr_QrCodeRelate._.IsDelete == false
                            && qr_QrCodeRelate._.rel_Code == o.nc_code);

                        if (!has)
                        {
                            #region 如果在关联表没有NC对应的记录，就新增二维码

                            //查询是否有以前弃用的二维码
                            var oldqr = qr_QrCodeService.Instance.Get_Entitys_ByTop(1, qr_QrCode._.type == 1 &&
                                qr_QrCode._.isdelete == true, qr_QrCode._.scene_id.Asc);

                            if (oldqr.IsNullOrCountLTE0())
                            {
                                #region 使用新的

                                #region get sceneid
                                var sceneid = 0;
                                qr_QrCodeType type = qr_QrCodeTypeService.Instance.Get_SingleEntity_byWhere(qr_QrCodeType._.QrCodeTypeID == 1);
                                sceneid = type.QT_CurrentIndex.ConvertTo<int>() + 1;
                                #endregion

                                #region 编辑图文信息
                                var extra = new List<extra>() { 
                                new extra { 
                                    title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                    shortdesc = "一键注册，终身礼遇", 
                                    linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=188$NCCode="+o.nc_code+"$openId=####", 
                                    picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                },
                                new extra{
                                    title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                    shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                    picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                },
                                new extra{
                                    title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                    shortdesc = "惊喜连连，准备好了么？", 
                                    linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                    picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                }
                            };
                                var message = new message()
                                {
                                    title = o.name,
                                    remark = o.name + "的二维码",
                                    sacode = "test",
                                    scene_id = sceneid.ToString(),
                                    extra = extra
                                };
                                #endregion

                                #region 请求vigo 生成二维码
                                var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                var resultentity = vigo.CreateQrcode(message);
                                #endregion

                                while (resultentity.errcode == "10")
                                {
                                    ComLib.LogLib.Log4NetBase.Log("二维码sceneid重复" + sceneid);
                                    sceneid += 1;
                                    message.scene_id = sceneid.ToString();
                                    resultentity = vigo.CreateQrcode(message);
                                }

                                #region 将返回的信息保存
                                if (resultentity.errcode == "00")
                                {
                                    #region 保存二维码
                                    qr_QrCode qrcode = new qr_QrCode()
                                    {
                                        id = resultentity.message.id,
                                        type = 1,
                                        scene_id = resultentity.message.scene_id,
                                        sacode = resultentity.message.sacode,
                                        title = resultentity.message.title,
                                        remark = resultentity.message.remark,
                                        code_url = resultentity.message.code_url,
                                        qrcode_url = resultentity.message.qrcode_url,
                                        addtime = resultentity.message.addtime,
                                        status = resultentity.message.status,
                                        DateModified = DateTime.Now,
                                        wx_title = "【美赞臣】微信注册",
                                        wx_content = "注册成为会员，享受更多优惠折扣！",
                                        wx_url = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=188$NCCode=" + o.nc_code + "$openId=####",
                                        wx_imgurl = "http://admin.mjn.howjoin.com/images/logo_b.png",
                                        isdelete = false
                                    };
                                    qr_QrCodeService.Instance.Add_Entity(qrcode);
                                    #endregion

                                    #region 添加关联
                                    qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                    {
                                        qr_Type = 1,//1是NC
                                        qr_CodeID = resultentity.message.id,
                                        qr_Scene_ID = resultentity.message.scene_id,
                                        rel_Code = o.nc_code,
                                        IsDelete = false,
                                        CreateOn = DateTime.Now
                                    };
                                    qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                    #endregion

                                    #region 更改二维码类型表
                                    type.QT_CurrentIndex = sceneid;
                                    type.QT_Used = type.QT_Used + 1;
                                    type.QT_Surplus = type.QT_Surplus - 1;
                                    qr_QrCodeTypeService.Instance.Update_Entity(type);
                                    #endregion
                                }
                                #endregion

                                ComLib.LogLib.Log4NetBase.Log("3、====新增NC二维码========新增===NCCode:" + o.nc_code + "::==sceneid==" + resultentity.message.scene_id);

                                #endregion
                            }
                            else
                            {
                                #region 使用弃用的

                                var qr = oldqr[0];

                                #region 更新二维码

                                #region 编辑图文信息
                                var extra = new List<extra>() { 
                                    new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=188$NCCode="+o.nc_code+"$openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                                };
                                var message = new message2()
                                {
                                    id = qr.id.ToString(),
                                    title = o.name,
                                    remark = o.name + "的二维码",
                                    sacode = o.name + "的二维码",
                                    extra = extra
                                };
                                #endregion

                                var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                var result = vigo.UpdateQrcode(message);

                                #region 修改弃用的二维码状态为启用
                                qr.title = o.name;
                                qr.remark = o.name + "的二维码";
                                qr.isdelete = false;
                                qr.DateModified = DateTime.Now;
                                qr.wx_title = "【美赞臣】微信注册";
                                qr.wx_content = "注册成为会员，享受更多优惠折扣！";
                                qr.wx_url = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=188$NCCode=" + o.nc_code + "$openId=####";
                                qr.wx_imgurl = "http://admin.mjn.howjoin.com/images/logo_b.png";
                                qr_QrCodeService.Instance.Update_Entity(qr);
                                #endregion

                                #endregion

                                #region 新建关联
                                qr_QrCodeRelate qrrelate = new qr_QrCodeRelate()
                                    {
                                        qr_Type = 1,//1是NC
                                        qr_CodeID = qr.id,
                                        qr_Scene_ID = qr.scene_id,
                                        rel_Code = o.nc_code,
                                        IsDelete = false,
                                        CreateOn = DateTime.Now
                                    };
                                qr_QrCodeRelateService.Instance.Add_Entity(qrrelate);
                                #endregion

                                ComLib.LogLib.Log4NetBase.Log("3、====NC为活跃，使用旧的二维码：：：NCCode：：" + o.nc_code + "::==sceneid==::" + qrrelate.qr_Scene_ID);
                                
                                #endregion
                            }
                            #endregion
                        }
                        else
                        {
                            #region 如果有了二维码，也更新一次
                            var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                            qr_QrCodeRelate._.qr_Type == 1 && qr_QrCodeRelate._.IsDelete == false
                            && qr_QrCodeRelate._.rel_Code == o.nc_code);

                            if (relate != null)
                            {
                                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                                if (qrcode != null)
                                {
                                    #region 更新二维码

                                    #region 编辑图文信息
                                    var extra = new List<extra>() { 
                                        new extra { 
                                            title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                            shortdesc = "一键注册，终身礼遇", 
                                            linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?regSubChannel=188$NCCode="+o.nc_code+"$openId=####", 
                                            picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                        },
                                        new extra{
                                            title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                            shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                            linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                            picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                        },
                                        new extra{
                                            title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                            shortdesc = "惊喜连连，准备好了么？", 
                                            linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                            picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                        }
                                    };
                                    var message = new message2()
                                    {
                                        id = qrcode.id.ToString(),
                                        title = o.name,
                                        remark = o.name + "的二维码",
                                        sacode = o.name + "的二维码",
                                        extra = extra
                                    };
                                    #endregion

                                    var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                    var result = vigo.UpdateQrcode(message);
                                    #endregion

                                    ComLib.LogLib.Log4NetBase.Log("3、====NC二维码修改：：：NCCode：：" + o.nc_code + "::==sceneid==::" + relate.qr_Scene_ID);
                                }
                            }
                            #endregion
                        }
                        #endregion
                    }
                    else
                    {
                        #region 离职员工的处理

                        var relate = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                            qr_QrCodeRelate._.qr_Type == 1 && qr_QrCodeRelate._.IsDelete == false
                            && qr_QrCodeRelate._.rel_Code == o.nc_code);

                        if (relate != null)
                        {
                            var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.id == relate.qr_CodeID);
                            if (qrcode != null)
                            {
                                #region 更新二维码，将二维码改成弃用

                                #region 编辑图文信息
                                var extra = new List<extra>() { 
                                    new extra { 
                                        title = "马上加入美赞臣A＋妈妈会，尊享360°孕育礼遇", 
                                        shortdesc = "一键注册，终身礼遇", 
                                        linkurl = "http://crmweb.meadjohnson.com.cn/mjnwx/client_phone.action?openId=####", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p1.jpg" 
                                    },
                                    new extra{
                                        title = "不可错过的海量专业孕育课程＆胎教早教资源！", 
                                        shortdesc = "有声资源每周更新，满足妈妈＆宝宝共同需求", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=2$sn=0d2328393e16964b17e11e30bb85378f$scene=1$srcid=06209qW7BXxURv3bBLvzMGHZ", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p2.jpg" 
                                    },
                                    new extra{
                                        title = "【会员福利】奶粉、京东优惠券、巧虎礼包、滴滴红包等你拿,还有……", 
                                        shortdesc = "惊喜连连，准备好了么？", 
                                        linkurl = "http://mp.weixin.qq.com/s?__biz=MjM5MjM1NjMzNA==$mid=2656105052$idx=3$sn=8478a978359403d68c1452f132455d32$scene=1$srcid=0620AZL0kIEOrjKTGX6Y2emW", 
                                        picurl = "http://admin.mjn.howjoin.com/images/p3.jpg" 
                                    }
                                };
                                var message = new message2()
                                {
                                    id = qrcode.id.ToString(),
                                    title = o.name,
                                    remark = o.name + "的旧二维码",
                                    sacode = o.name + "的旧二维码",
                                    extra = extra
                                };
                                #endregion

                                var vigo = new Qrcode_vigo(this.httpstr, this.signserect);
                                var result = vigo.UpdateQrcode(message);

                                #region 修改的启用二维码状态为弃用
                                qrcode.isdelete = true;
                                qrcode.DateModified = DateTime.Now;
                                qrcode.wx_title = "";
                                qrcode.wx_content = "";
                                qrcode.wx_url = "";
                                qrcode.wx_imgurl = "";
                                qr_QrCodeService.Instance.Update_Entity(qrcode);
                                #endregion

                                #endregion

                                #region 修改关联成删除
                                relate.IsDelete = true;
                                relate.DateModified = DateTime.Now;
                                qr_QrCodeRelateService.Instance.Update_Entity(relate);
                                #endregion

                                ComLib.LogLib.Log4NetBase.Log("3、====NC离职，将此二维码弃用：：：NCCode：：" + o.nc_code + "::==sceneid==::" + relate.qr_Scene_ID);
                            }
                        }

                        #endregion
                    }

                    #region 将nc置为已修改
                    o.isneedupdate = false;
                    nc_ncuserService.Instance.Update_Entity(o);
                    #endregion
                }
                catch (Exception ex)
                {
                    ComLib.LogLib.Log4NetBase.Log("更新一个二维码错误::::" + ex.Message + ex.StackTrace);
                }
            });
        }
    }
}
